<template>
  <basic-dialog
    :width="'75%'"
    :visible="visible"
    :title="'添加供应商'"
    :show-footer="false"
    :handle-close="onCancel"
    :handleOpened="handleOpened"
  >
    <div class="form-container">
      <el-form
        size="mini"
        ref="searchForm"
        :model="searchForm"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input
                v-model="searchForm.supplierName"
                placeholder="供应商名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商代码" prop="supplierCode">
              <el-input
                v-model="searchForm.supplierCode"
                placeholder="供应商代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合作品牌" prop="cooperationBrand">
              <el-input
                v-model="searchForm.cooperationBrand"
                placeholder="合作品牌"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经营品类" prop="manageCategoryCodes">
              <SelectCategory
                ref="mainCategory"
                @onSelected="handleCategorySelected"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否协同" prop="onlineCollaboration">
              <el-select
                v-model="searchForm.onlineCollaboration"
                style="width: 100%"
              >
                <el-option
                  v-for="option in ONLINE_COLLABORATION_OPTIONS"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="进货状态" prop="purchaseStatus">
              <el-select
                v-model="searchForm.purchaseStatus"
                style="width: 100%"
              >
                <el-option
                  v-for="option in PURCHASE_STATUS_OPTIONS"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="主营商品" prop="mainCommodities">
              <el-input
                v-model="searchForm.mainCommodities"
                placeholder="主营商品"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="20px">
              <el-button size="mini" type="primary" @click="handleQuerySupplier" :disabled="isRecommendTab">查询</el-button>
              <el-button size="mini" @click="handleReset('searchForm')">重置</el-button>
              <el-button size="mini"
                type="primary"
                :loading="addSupplierLoading || submitLoading"
                @click="confirmHandler"
              >确认添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-tabs v-if="showRecommendTab" v-model="tabInfo.selectedTab" @tab-click="handleSwitchTabs">
      <el-tab-pane
        v-for="item in tabInfo.list"
        v-model="item.name"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :disabled="tableInfo.loading"
      />
    </el-tabs>
    <BasicList
      :loading="tableInfo.loading"
      :data-source="tableInfo.list"
      :columns="TABLE_COLUMNS"
      :tableHeight="460"
      showActionCol
      :actionRender="actionRender"
      :total="tableInfo.total"
      :selection-change="selectionChange"
      :showPagination="!isRecommendTab"
      :pagination="pagenation"
      @pageChange="pageChange"
      @pageSizeSelect="pageSizeSelect"
    />
  </basic-dialog>
</template>
<script>
import { mapState } from 'vuex';
import BasicDialog from '../BasicDialog';
import BasicList from '../BasicList';
import SelectCategory from '@/components/Category/SingleSelect';
import { TABLE_COLUMNS, PURCHASE_STATUS_OPTIONS, ONLINE_COLLABORATION_OPTIONS } from './constants';
import { getRecommendSupplierService, getSupplierService } from '@api/sourcing/purchaseDetail';

export default {
  name: 'QuoteDialog',
  components: {
    BasicDialog,
    BasicList,
    SelectCategory
  },
  props: {
    dialogVisible: {
      type: Boolean,
    },
    showRecommendTab: {
      type: Boolean,
      default: false
    },
    sourcingBillId: {
      type: [String, Number]
    },
    submitLoading: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      TABLE_COLUMNS,
      PURCHASE_STATUS_OPTIONS,
      ONLINE_COLLABORATION_OPTIONS,
      tabInfo: {
        selectedTab: '',
        list: [
          { title: '推荐供应商', name: '10' },
          { title: '全部供应商', name: '20' },
        ],
      },
      tableInfo: {
        loading: false,
        list: [],
        total: 0
      },
      selectRows: [],
      searchForm: {
        supplierName: '',
        supplierCode: '',
        cooperationBrand: '',
        mainCommodities: '',
        onlineCollaboration: '',
        manageCategoryCodes: [],
        purchaseStatus: 1031,
      },
      pagenation: {
        pageSize: 50,
        pageNum: 1,
      },
    };
  },

  computed: {
    ...mapState('sourcing/purchaseDetail', {
      addSupplierLoading: (state) => state.addSupplierLoading,
    }),
    visible () {
      return this.dialogVisible;
    },
    isRecommendTab () {
      return this.tabInfo.selectedTab == 10
    }
  },
  methods: {
    actionRender (h, { row }) {
      return (
        <div class="table-action">
          <el-button
            size="mini"
            type="text"
            loading={this.addSupplierLoading || this.submitLoading}
            onClick={() => this.addSupplierHandler(row)}
          >添加</el-button>
        </div>
      );
    },
    // 经营品类选择
    handleCategorySelected (data) {
      if (data) {
        const { categoryNo } = data;
        this.searchForm.manageCategoryCodes = [categoryNo];
      } else {
        this.searchForm.manageCategoryCodes = [];
      }
    },
    // tab 切换
    handleSwitchTabs (type) {
      this.tableInfo.list = [];
      this.tableInfo.total = 0;
      if (type.name == 10) {
        this.queryRecommendSupplier()
      }
      if (type.name == 20) {
        this.handleQuerySupplier()
      }
    },
    handleOpened () {
      if (this.showRecommendTab) {
        // 推荐供应商
        this.tabInfo.selectedTab = '10';
      } else {
        this.tabInfo.selectedTab = '20';
      }
      this.$refs.mainCategory.clearCategoryNodes();
      this.handleSwitchTabs({ name: this.tabInfo.selectedTab })
    },
    selectionChange (rows) {
      this.selectRows = rows;
    },
    // 批量添加
    confirmHandler () {
      if (this.selectRows.length === 0) {
        return this.$message.warning('请选择要添加的供应商')
      }
      // 1032停止,1031正常
      if (this.selectRows.some(item => item.purchaseStatus == 1032)) {
        return this.$message.warning('供应商中存在停止进货的供应商，请清除后重试')
      }
      // black 是否拉黑0：否 1：是
      if (this.selectRows.some(item => item.black == 1)) {
        return this.$message.warning('供应商中存在已拉黑的供应商，请清除后重试')
      }
      // eliminate 是否淘汰 0：否 1：是
      if (this.selectRows.some(item => item.eliminate == 1)) {
        return this.$message.warning('供应商中存在已淘汰的供应商，请清除后重试')
      }
      // 加工供应商提示
      if (this.selectRows.some(item => item.supplierType == 1002)) {
        return this.handleConfirm(this.selectRows)
      }
      this.$emit('add-supplier', this.selectRows)
    },
    // 逐条添加
    addSupplierHandler (row) {
      let selectSupplierList = [];
      selectSupplierList.push(row);
      // 1032停止,1031正常
      if (row.purchaseStatus == 1032) {
        return this.$message.warning('此供应商是停止进货供应商，若需询价订货联系对应商品主管')
      }
      // black 是否拉黑0：否 1：是
      if (row.black == 1) {
        return this.$message.warning('此供应商已拉黑，不能添加询价')
      }
      // eliminate 是否淘汰 0：否 1：是
      if (row.eliminate == 1) {
        return this.$message.warning('此供应商已淘汰，不能添加询价')
      }
      // 加工供应商提示
      if (row.supplierType == 1002) {
        return this.handleConfirm(selectSupplierList)
      }
      this.$emit('add-supplier', selectSupplierList)
    },
    // 加工供应商判断
    handleConfirm (supplierList) {
      return this.$confirm(
        '选中的供应商存在加工供应商，只能做委托加工采购订单，请确认该单据是否委外加工业务？',
        { title: '提示', type: 'warning' }
      ).then(() => {
        this.$emit('add-supplier', supplierList)
      }).catch(() => {});
    },
    // 查询全部供应商
    handleQuerySupplier () {
      this.pagenation = {
        pageSize: 50,
        pageNum: 1,
      }
      this.querySupplierList()
    },
    onCancel () {
      this.emptyForm();
      this.$emit('hide-handler');
    },
    emptyForm () {
      // 重置表单
      this.searchForm = {
        supplierName: '',
        supplierCode: '',
        cooperationBrand: '',
        mainCommodities: '',
        onlineCollaboration: '',
        manageCategoryCodes: [],
        purchaseStatus: 1031,
      };
      this.pagenation = {
        pageSize: 50,
        pageNum: 1,
      };
      this.selectRows = [];
    },
    pageChange (current) {
      this.pagenation.pageNum = current;
      this.querySupplierList();
    },
    // 页码选择
    pageSizeSelect (length) {
      this.pagenation.pageSize = length;
      this.querySupplierList();
    },
    handleReset (formName) {
      this.$refs[formName].resetFields();
      this.$refs.mainCategory.clearCategoryNodes();
    },
    // 获取推荐供应商
    async queryRecommendSupplier () {
      const res = await getRecommendSupplierService({ sourcingBillId: this.sourcingBillId }, state => { this.tableInfo.loading = state })
      if (res) {
        this.tableInfo.list = res.data || [];
      }
    },
    // 获取推荐供应商
    async querySupplierList () {
      const res = await getSupplierService({ ...this.searchForm, ...this.pagenation }, state => { this.tableInfo.loading = state })
      if (res?.data) {
        const { data, totalNum } = res.data;
        this.tableInfo.list = data;
        this.tableInfo.total = totalNum;
      }
    }
  },
};
</script>
